package org.bsuir.filespocket.view;

import org.bsuir.filespocket.model.User;
import org.bsuir.filespocket.service.UserDAO;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EditUserController extends SimpleFormController {

    private UserDAO userDAO;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        int userId = -1;
        try {
            userId = Integer.parseInt(request.getParameter("userId"));
        } catch (NumberFormatException e) {}
        User user = userDAO.findUser(userId);

        return user;
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse httpServletResponse,
                                    Object o, BindException e) throws Exception {
        User newUser = (User) o;
        userDAO.saveUser(newUser);

        return new ModelAndView(new RedirectView(getSuccessView()));
    }

}
